package com.kobold.rules.groovy;


import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilerConfiguration;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class GroovyScriptProvider {
    private static final Map<Integer, Script> scriptCache = new HashMap<>();

    public static Script getScript(String expression, CompilerConfiguration compilerConfiguration) {
        Objects.requireNonNull(expression);
        if (compilerConfiguration instanceof GroovyCompilerConfiguration) {
            GroovyCompilerConfiguration groovyCompilerConfiguration = (GroovyCompilerConfiguration) compilerConfiguration;
            if (groovyCompilerConfiguration.isEnableCache()) {
                Integer scriptHashCode = expression.hashCode();
                Script script = scriptCache.get(scriptHashCode);
                if (Objects.isNull(script)) {
                    script = new GroovyShell(groovyCompilerConfiguration).parse(expression);
                    scriptCache.put(scriptHashCode, script);
                }
                return script;
            } else {
                return new GroovyShell(groovyCompilerConfiguration).parse(expression);
            }
        }
        return new GroovyShell(compilerConfiguration).parse(expression);

    }

}
